$(function () {
  const form = layui.form

  const key = {
    start_time: '',
    end_time: "",
    title: '',
    cateid: '',
    page: 1,
    limit: 10,
  }


  getlist()
  function getlist() {
    axios({
      method: 'get',
      url: '/ydd_article/list',
      params: key,
      headers: { 'x-token': localStorage.getItem('x-token') }
    }).then(({ status, data: { errno, errmsg, data: { data, count } } }) => {


      // console.log(data);
      // console.log(status);
      $('#num').html(count)
      const newarr = data.map(({ catename, id, ishot, istop, create_date, title, status, pic }) => {
        if (status === 0) {
          status = '待审核'
        } else if (status === 1) {
          status = '草稿箱'
        } else if (status === 2) {
          status = '已发布'
        } else if (status === 3) {
          status = '已删除'
        }

        if (istop === 1) {
          istop = 'checked',
            ishot = 'checked'
        } else {
          istop = ''
        }
        // console.log(id);
        return `  <tr>
        <td>${id}</td>
        <td>${title}</td>
        <td>${catename ? catename : ''}</td>
        <td>${pic ? `<img src="http://124.223.14.236:8060/${pic}" alt="">` : ''}</td>
        <td>${new Date(+create_date).toLocaleDateString().replace(/\//g, '-')}</td>
        <td>
        <input type="checkbox" name="switch"  lay-skin="switch" ${ishot ? 'checked' : ''}>
        </td>
        <td>
          <input type="checkbox" name="switch" lay-skin="switch" ${istop}>
        </td>
        <td>
          <button class="status">${status}</button>
        </td>
        <td>
          <ul class="right handler">
            <li class="change" data-id=${id}>
              <i class="layui-icon layui-icon-edit"></i>
            </li>
            <li class="del" data-id=${id}>
              <i class="layui-icon layui-icon-delete"></i>
            </li>
          </ul>
        </td>
      </tr>
   `
      }).join('')
      $('tbody').html(newarr)

      layui.use('laypage', function () {
        const laypage = layui.laypage
        // console.log("laypage:", laypage)
        // 分页器

        laypage.render({
          elem: 'page', //注意，这里的 test1 是 ID，不用加 # 号
          count: count,//数据总数，从服务端得到
          limit: key.limit,
          curr: key.page,
          limits: [10, 20, 40, 50], // 如果 layout 参数开启了 limit，则会出现每页条数的select选择框
          layout: ['limit', 'prev', 'page', 'next', 'skip'],//自定义排版,页面显示元素
          // 分页器的每项值改动都会调用这个回调函数
          jump: (obj, first) => { // obj 为每次分页器改变后的新值,
            // first来控制是过滤只要分页器直接改变时才执行的代码
            key.page = obj.curr
            key.limit = obj.limit
            //首次不执行
            if (!first)
              getlist()

          }
        });
      })
    })
  }


  //重置=================
  $('#reset').on('click', () => {
    const obj = {
      start_time: '',
      end_time: "",
      title: '',
      cateid: '',
      page: 1,
      limit: 10,
    }
    Object.assign(key, obj)
    getlist()
    $('#search')[0].reset()
  })

  // 点击删除
  $('tbody').on('click', '.del', function () {
    const id = $(this).attr('data-id')
    // console.log(id);
    axios.get(`/ydd_article/del?id=${id}`).then(({ errmsg, errno }) => {
      // console.log(res);
      if (errno) return layer.msg(errmsg, { icon: 5, time: 1000 })
      layer.confirm('确认删除吗?', index => {
        getlist()
        layer.close(index)
      });
    })

  })

  //搜索================================================================
  $('#search').on('submit', function (e) {
    e.preventDefault()
    // const data = {}
    // const regs = /[^\u4E00-\u9FA5]/g;
    // const tagname1 = $('#tags').val()
    const tagname2 = $('.search').serialize().split('&').map((item) => item.split('='))

    // console.log(tagname2[1][1]);

    key.title = tagname2[0][1]
    key.cateid = tagname2[1][1]
    key.page = 1
    getlist()
  })
  // 分类栏===========================================================
  axios.get('/ydd_cate/all').then(({ data: { data } }) => {
    // console.log(data);
    $('[name="cateid"]').append(data.map(({ catename, id }) => catename ? `
      <option  value="${id}" >${catename}</option>` : '').join(''))
    form.render()
  })
  getlist()

  //时间获取=======================
  layui.use('form', function () {

    //监听提交
    // form.on('submit(formDemo)', function(data){
    //   layer.msg(1111);
    //   return false;
    // });

    layui.use('laydate', function () {

      let laydate = layui.laydate;
      //执行一个laydate实例
      laydate.render({
        elem: '#startDate' //指定元素
      });

      //执行一个laydate实例
      laydate.render({
        elem: '#endDate' //指定元素
      });
    });
  });



  $('#close').on('click', function () {
    $('.search').toggle()
    $('#close').hide()
    $('#open').show()
  })

  $('#open').on('click', function () {
    $('.search').show()
    $('#open').hide()
    $('#close').show()
  })

  $('#SX').on('click', function () {
    self.location.reload()
  })





  //搜索和编辑======================
  $('.list .add').on('click', () => location.href = '/youdianda_static/article.add.html')

  $('tbody').on('click', '.change', function () {
    const id = $(this).data('id')
    localStorage.setItem('articleId', id)
    location.href = '/youdianda_static/article.change.html'
  })

})